<template>
  <div id="LessonDetail">
    <a-form layout="inline" style="margin-bottom: 8px">
      <a-form-item label="" class="searchItem">
        <span style="color: white"> {{ detailData.planName }}</span>
      </a-form-item>
      <a-form-item label="">
        <a-button type="primary" @click="addbtn">
          <span v-if="detailData.type == '课程资源'">添加课程资源</span>
          <span v-if="detailData.type == '训练计划'">添加训练计划</span>
          <!-- 添加课程计划资源  -->
        </a-button>
        <a-button type="primary" style="margin-left: 10px" @click="backup">
          返回
        </a-button>
      </a-form-item>
    </a-form>
    <a-table
      v-if="detailData.type == '课程资源'"
      bordered
      :scroll="{ y: 500 }"
      :columns="columns"
      style="margin-top: 16px"
      :data-source="tableData"
      :pagination="tablePagination"
      :rowKey="(record, index) => index"
      @change="handleTableChange"
    >
      <template slot="name" slot-scope="text, record">
        <a-tooltip placement="top" v-if="record.name">
          <template slot="title">
            <span>{{ record.name }}</span>
          </template>
          <span style="cursor: default">{{ record.name }}</span>
        </a-tooltip>
        <span v-else-if="!record.name">—</span>
      </template>
      <template slot="tapdProjectId" slot-scope="text, record">
        <a-tooltip placement="top" v-if="record.tapdProjectId">
          <template slot="title">
            <p>{{ record.tapdProjectId }}</p>
          </template>
          <span style="cursor: default">{{ record.tapdProjectId }}</span>
        </a-tooltip>
        <span v-else-if="!record.tapdProjectId">—</span>
      </template>
      <template slot="operation" slot-scope="text, record">
        <div v-if="$store.state.userData.roleName == 'educator'">
          <a-button
            v-if="record.operation"
            type="primary"
            @click="downLoad(record)"
            >下载</a-button
          >
          <a-button
            v-if="record.operation"
            type="danger"
            @click="deleteClick(record)"
            style="margin-left: 10px"
            >删除</a-button
          >
        </div>
        <div v-if="$store.state.userData.roleName == 'student'">
          <a-button type="primary" @click="downLoad(record)">下载</a-button>
        </div>
      </template>
    </a-table>
    <a-table
      v-if="detailData.type == '训练计划'"
      bordered
      :scroll="{ y: 500 }"
      :columns="columns2"
      style="margin-top: 16px"
      :data-source="tableData"
      :pagination="tablePagination"
      :rowKey="(record, index) => index"
      @change="handleTableChange"
    >
      <template slot="name" slot-scope="text, record">
        <a-tooltip placement="top" v-if="record.name">
          <template slot="title">
            <span>{{ record.name }}</span>
          </template>
          <span style="cursor: default">{{ record.name }}</span>
        </a-tooltip>
        <span v-else-if="!record.name">—</span>
      </template>
      <template slot="tapdProjectId" slot-scope="text, record">
        <a-tooltip placement="top" v-if="record.tapdProjectId">
          <template slot="title">
            <p>{{ record.tapdProjectId }}</p>
          </template>
          <span style="cursor: default">{{ record.tapdProjectId }}</span>
        </a-tooltip>
        <span v-else-if="!record.tapdProjectId">—</span>
      </template>
      <template slot="operation" slot-scope="text, record">
        <a-button type="primary" @click="begainExamine(record)"
          >开始考核</a-button
        >
        <a-button
          type="danger"
          @click="deleteClick(record)"
          style="margin-left: 10px"
          >删除</a-button
        >
      </template>
    </a-table>
    <a-modal
      v-model="visible"
      :maskClosable="false"
      :title="title"
      @cancel="handleCancel"
    >
      <a-form-model
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 12 }"
        ref="formRef"
        :model="form"
        :rules="rules"
      >
        <a-form-model-item :label="detailData.type" prop="ids">
          <a-select
            v-model="form.ids"
            mode="multiple"
            style="width: 300px"
            :maxTagCount="1"
          >
            <a-select-option
              v-for="item in fileList"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button key="back" class="modalCancel" @click="handleCancel"
          >取消</a-button
        >
        <a-button key="submit" @click="primaryClick" type="primary">
          确定
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import moment from "moment";
export default {
  props: {
    detailData: {},
  },
  data() {
    return {
      fileList: [],
      form: {
        ids: [], //文件资源
      },
      rules: {
        // ids: [{ required: true, message: "请选择文件资源", trigger: "blur" }],
      },
      visible: false,
      title: null,
      columns2: [
        //主页table列的配置
        {
          title: "序列号",
          dataIndex: "key",
          scopedSlots: { customRender: "key" },
        },
        {
          title: "科目名称",
          dataIndex: "name",
          customRender: (text, record) => {
            return record.name ? record.name : "—";
          },
        },
        {
          title: "路径",
          dataIndex: "path",
          customRender: (text, record) => {
            return record.path ? record.path : "—";
          },
        },
        {
          title: "操作",
          align:"center",
          width: 300,
          dataIndex: "operation",
          scopedSlots: { customRender: "operation" },
        },
      ],
      columns: [
        //主页table列的配置
        {
          title: "序列号",
          dataIndex: "key",
          scopedSlots: { customRender: "key" },
        },
        {
          title: "资源名称",
          dataIndex: "fileName",
          customRender: (text, record) => {
            return record.fileName ? record.fileName : "—";
          },
        },
        {
          title: "资源类型",
          dataIndex: "fileType",
          customRender: (text, record) => {
            return record.fileType ? record.fileType : "—";
          },
        },
        {
          title: "资源地址",
          dataIndex: "filePath",
          customRender: (text, record) => {
            return record.filePath ? record.filePath : "—";
          },
        },
        {
          title: "操作",
          align:"center",
          width: 300,
          dataIndex: "operation",
          scopedSlots: { customRender: "operation" },
        },
      ],
      tableData: [
        //主页表格的数据
      ],
      tablePagination: {
        //主页表格的分页器
        total: 0,
        current: 1,
        pageSize: 10,
        showQuickJumper: true, //是否可以快速跳转至某页
        showSizeChanger: true, //是否可以改变 pageSize
      },
    };
  },
  created() {
    this.getData();
    this.getFileList();
  },
  methods: {
    begainExamine(row) {
      if (row.type == 1) {
        //在线理论考核
        this.$router.push({ name: "OnlineTheory", query: { data: row } });
      } else if (row.type == 2) {
        //在线实操考核
        let str =
          "&trainingId=" +
          row.id +
          "&Authorization=" +
          localStorage.getItem("token");
        let url = row.path + str;
        window.open(url);
      }
    },
    handleTableChange(pagination, filters, sorter) {
      this.tablePagination.current = pagination.current;
      this.tablePagination.pageSize = pagination.pageSize;
      this.getData();
    },
    downLoad(row) {
      this.$axios
        .get("/curriculum/resource/download", {
          params: {
            id: row.id,
          },
          responseType: "blob", // 关键：指定返回数据类型为 blob
        })
        .then((res) => {
          const downloadUrl = window.URL.createObjectURL(res);
          const link = document.createElement("a"); // 创建隐藏的下载链接
          link.href = downloadUrl;
          const filename = row.fileName; //文件名可以从响应头或请求参数中获取
          link.download = filename;
          link.click();
          link.remove();
        });
    },
    getFileList() {
      let url = null;
      let id = null;
      if (this.detailData.type == "课程资源") {
        url = "/curriculum/resource/options";
        id = this.detailData.curriculumId;
      } else if (this.detailData.type == "训练计划") {
        url = "/training/plan/options";
      }
      this.$axios
        .get(url, {
          params: {
            id,
          },
        })
        .then((res) => {
          this.fileList = res.data;
        });
    },
    deleteClick(row) {
      //点击删除
      let url = null;
      if (this.detailData.type == "课程资源") {
        url = "/curriculum/resource/delete";
      } else if (this.detailData.type == "训练计划") {
        url = "/training/plan/delete";
      }
      let that = this;
      this.$confirm({
        title: "确认删除?",
        content: "您确定要删除此项吗?",
        onOk() {
          that.$axios
            .delete(url, {
              data: {
                id: row.id,
              },
            })
            .then((res) => {
              if (res.code == 200) {
                that.$message.success("删除成功");
                that.getData();
              }
            });
        },
        onCancel() {
          console.log("取消删除");
        },
      });
    },
    editClick(row) {
      //编辑
      for (let i in row) {
        if (i in this.form && i != "time") {
          this.form[i] = row[i];
        }
      }
      this.title = "编辑";
      this.visible = true;
    },
    addbtn() {
      //添加课程计划资源
      this.title = "添加课程计划资源";
      this.visible = true;
    },
    handleCancel() {
      this.form = {
        ids: [], //文件资源
      };
      this.visible = false;
    },
    primaryClick() {
      // let resourceIds =
      //   this.form.ids.length > 0
      //     ? this.form.ids.filter((item) => item != null).join(",")
      //     : null;
      let resourceIds = this.form.ids;
      this.$nextTick(() => {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            let data = null;
            let url = null;
            if (this.detailData.type == "课程资源") {
              url = "/curriculum/plan/set/resource";
              data = {
                resourceIds, //课程资源ID(下拉框出来的)
                id: this.detailData.id, //课程基本信息ID(从父级带过来)
              };
            } else if (this.detailData.type == "训练计划") {
              url = "/curriculum/plan/set/training";
              data = {
                trainingIds: resourceIds, //课程资源ID(下拉框出来的)
                id: this.detailData.id, //课程基本信息ID(从父级带过来)
              };
            }
            if (this.title == "添加课程计划资源") {
              this.$axios.post(url, data).then((res) => {
                if (res.code == "200") {
                  this.$message.success("新增成功");
                  this.getData();
                  this.handleCancel(); // 关闭模态框
                } else {
                  this.$message.warning(res.message);
                }
              });
            } else if (this.title == "编辑") {
              this.$axios.put("/sys/coursePlane", data).then((res) => {
                if (res.code == 200) {
                  this.$message.success("编辑成功");
                  this.getData();
                  this.handleCancel(); // 关闭模态框
                }
              });
            }
          } else {
            console.log("校验失败");
          }
        });
      });
    },
    async getData() {
      let url = "";
      if (this.detailData.type == "课程资源") {
        url = "/curriculum/resource/page/list";
      } else if (this.detailData.type == "训练计划") {
        url = "/training/plan/page/list";
      }
      let { data } = await this.$axios.get(url, {
        params: {
          planId: this.detailData.id,
          page: this.tablePagination.current,
          size: this.tablePagination.pageSize,
        },
      });
      data.records.forEach((item, index) => {
        item.key = index + 1;
      });
      if (this.detailData.type == "训练计划") {
        // data.records.forEach((item) => {
        //   item.fileName = item.name;
        //   item.filePath = item.path;
        //   item.fileType = item.type;
        // });
      }
      this.tableData = data.records;
      this.tablePagination.total = data.total;
    },
    backup() {
      this.$emit("changeIsDetail", { status: false });
    },
  },
};
</script>

<style></style>